package org.example.everyday;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * Description:TODO 详细描述
 * <p>
 * Copyright: 天津联想协同科技有限公司
 * <p>
 *
 * @author anlu
 * @date 2022/2/9 18:07
 */
public class CountKDifference {

    public static void main(String[] args) {
        CountKDifference c = new CountKDifference();

       int[] nums = new int[]{1,2,2,1};
       int k = 1;
       int result= c.countKDifference(nums,k);
        System.out.println(result);
    }


    public int countKDifference(int[] nums, int k) {
        int res = 0,n=nums.length;
        Map<Integer,Integer> cnt = new HashMap<Integer,Integer>();
        for (int i = 0; i < n; i++) {
            res += cnt.getOrDefault(nums[i] - k,0) + cnt.getOrDefault(nums[i] + k,0);
            cnt.put(nums[i],cnt.getOrDefault(nums[i],0) + 1);
        }
        return res;
    }
}


// i(1) - j(2) = k1
/**
 * -1+2 = 1
 * 2-1 = 1
 *
 * 1-2 =-1
 * 2-1=1
 *
 */

